
//
//  MapViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/11.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "MapViewController.h"
#import "CBaseTable.h"
#import "Common.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
@interface MapViewController()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,BMKMapViewDelegate, BMKPoiSearchDelegate,BMKGeoCodeSearchDelegate>
{
    CBaseTable       *_table;
    UISearchBar      *_topSearchBar;
    BMKMapView* _mapView;
    BMKPoiSearch* _poisearch;
    NSMutableArray *_dataArray;
    BMKGeoCodeSearch * _geocodesearch;
    BMKPointAnnotation* pointAnnotation;
    BMKPointAnnotation* animatedAnnotation;
    BOOL                  isSearching;
    BOOL isGeoSearch;
    NSString *_searchText;
    NSMutableDictionary *_dict;
}
@end
@implementation MapViewController
-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _poisearch.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放

}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _poisearch.delegate = nil; // 不用时，置nil
}


- (void)initView
{
    [super initView];
    self.navBar.hidden=NO;
    [self setTitle:@"地理位置"];
    _dict =[[NSMutableDictionary alloc]init];

    __block typeof(_dict) blockself = _dict;
    __block typeof(self) blockself1 = self;

    [self.navBar setBackAction:^{
        if([blockself objectForKey:@"name"]) {
            //key1存在
            [blockself1 backController];

        } else {
            //key1 不存在
            [CClass showMessage:@"请选择一个地址"];
            return ;

        } 

//        if ([[blockself objectForKey:@"name"] isEqualToString:@""]) {
//            [CClass showMessage:@"请选择一个地址"];
//            return ;
//        }else
//        {
//            [blockself1 backController];
//
//        }
//        [blockself setObject:@"" forKey:@"name"];
//        [blockself setObject:@"" forKey:@"latitude"];
//        [blockself setObject:@"" forKey:@"longitude"];
//        [blockself setObject:@"" forKey:@"city"];
//        [blockself setObject:@"" forKey:@"province"];
//        blockself1.backLocation(blockself);
    }];
    _dataArray =[[NSMutableArray alloc]init];
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    //编码服务的初始化(就是获取经纬度,或者获取地理位置服务)
    _geocodesearch.delegate = self;//设置代理为self

    _topSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(25, 64+5, WindowWidth-50, 30)];
    _topSearchBar.placeholder = @"搜索";
    _topSearchBar.delegate = self;
    [Common setSearchBarStyle:_topSearchBar];
    [self.view addSubview:_topSearchBar];
    _poisearch = [[BMKPoiSearch alloc]init];
    _mapView =[[BMKMapView alloc]initWithFrame:CGRectMake(0, 110, WindowWidth, (WindowHeight-110)/2)];
    [self.view addSubview:_mapView];
    
//    [_mapView setZoomLevel:13];
    _mapView.isSelectedAnnotationViewFront = YES;
    //添加标注
    if (pointAnnotation == nil) {
        pointAnnotation = [[BMKPointAnnotation alloc]init];
        CLLocationCoordinate2D coor;
        coor.latitude = [[self.dataDic objectForKey:@"latitude"]doubleValue];
        coor.longitude = [[self.dataDic objectForKey:@"longitude"]doubleValue];
        NSLog(@"======%@",[self.dataDic objectForKey:@"longitude"]);

        pointAnnotation.coordinate = coor;
//        pointAnnotation.title = @"我的位置";
        [_mapView addAnnotation:pointAnnotation];
    }
    

    _table =[[CBaseTable alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_mapView.frame), WindowWidth, WindowHeight-CGRectGetMaxY(_mapView.frame))style:UITableViewStylePlain];
    _table.separatorStyle =UITableViewCellSelectionStyleNone;
    _table.delegate =self;
    _table.dataSource=self;
    _table.backgroundColor =[UIColor whiteColor];
    [self.view addSubview:_table];
    
    
    //地址转换为坐标
//    isGeoSearch = true;
//    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc]init];
//    geocodeSearchOption.address = searchBar.text;
//    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
//    if(flag)
//    {
//        NSLog(@"geo检索发送成功");
//    }
//    else
//    {
//        NSLog(@"geo检索发送失败");
//    }
    
  //第一次是坐标搜索
//    [self searchRusult:[self.dataDic objectForKey:@"address"]with:[[self.dataDic objectForKey:@"latitude"]doubleValue] with:[[self.dataDic objectForKey:@"longitude"]doubleValue]];
    //坐标转换成地址
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){[[self.dataDic objectForKey:@"latitude"]doubleValue], [[self.dataDic objectForKey:@"longitude"]doubleValue]};//初始化
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        echo(@"反geo检索发送成功");
    }
    else
    {
        echo(@"反geo检索发送失败");
    }
   

}
#pragma mark - UISearchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    isSearching = YES;
    return YES;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self didStopSearch];
}
//取消搜索
- (void)didStopSearch
{
    isSearching = NO;
    _topSearchBar.text = nil;
    [_topSearchBar resignFirstResponder];
}
//-(void)searchRusult:(NSString*)sting with:(double)latitude with:(double)longitude
//{
//    
//    //搜索周边的请求
//    BMKNearbySearchOption *searchOption = [[BMKNearbySearchOption alloc]init];
//    searchOption.location=CLLocationCoordinate2DMake(latitude,longitude);
//    searchOption.radius=10;
//    searchOption.keyword = sting;
//    BOOL flag = [_poisearch poiSearchNearBy:searchOption];
//    if (!flag) {
//        NSLog(@"周边检索失败");
//    }
//    
//}

//点击键盘搜素按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    _searchText = searchBar.text;
    
    BMKCitySearchOption *citySearchOption = [[BMKCitySearchOption alloc]init];
    citySearchOption.pageIndex = 0;
    citySearchOption.pageCapacity = 10;
    citySearchOption.city=[self.dataDic objectForKey:@"cityName"];
    citySearchOption.keyword = searchBar.text;
    BOOL flag = [_poisearch poiSearchInCity:citySearchOption];
    if(flag)
    {
        echo(([NSString stringWithFormat:@"城市内检索发送成功"]));
 
    }
    else
    {
        echo(([NSString stringWithFormat:@"城市内检索发送失败"]));

    }

    [searchBar resignFirstResponder];

    
}


#pragma mark -
#pragma mark implement BMKMapViewDelegate

/**
 *根据anntation生成对应的View
 *@param mapView 地图View
 *@param annotation 指定的标注
 *@return 生成的标注View
 */
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //普通annotation
    NSString *AnnotationViewID = @"renameMark";
    BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
    if (annotationView == nil) {
        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        annotationView.annotation=annotation;
        
        UIImage *img =[UIImage imageNamed:@"Ico_Loaction"];
        annotationView.frame =CGRectMake(0, 0, img.size.width, img.size.height);
        annotationView.image =img;
    }
    return annotationView;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    [mapView bringSubviewToFront:view];
    [mapView setNeedsDisplay];
}
- (void)mapView:(BMKMapView *)mapView didAddAnnotationViews:(NSArray *)views
{
}
/**
 *地图初始化完毕时会调用此接口
 *@param mapview 地图View
 */
- (void)mapViewDidFinishLoading:(BMKMapView *)mapView
{
    if ([[self.dataDic objectForKey:@"latitude"] isEqual:@""]&& [[self.dataDic objectForKey:@"longitude"] isEqual:@""]) {
        //北京天安门
        _mapView.centerCoordinate = CLLocationCoordinate2DMake(39.915175, 116.403906);
    }else
    {
    _mapView.centerCoordinate = CLLocationCoordinate2DMake([[self.dataDic objectForKey:@"latitude"]doubleValue], [[self.dataDic objectForKey:@"longitude"]doubleValue]);
    }
    
}
#pragma mark -
#pragma mark implement BMKSearchDelegate
//搜索结果
- (void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult*)result errorCode:(BMKSearchErrorCode)error
{

    // 清楚屏幕中所有的annotation
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
 
    [_dataArray removeAllObjects];
    if (error == BMK_SEARCH_NO_ERROR) {
        NSMutableArray *annotations = [NSMutableArray array];
        for (int i = 0; i < result.poiInfoList.count; i++) {
            BMKPoiInfo* poi = [result.poiInfoList objectAtIndex:i];
            BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
            item.coordinate = poi.pt;
            item.title = poi.name;
            item.subtitle =poi.address;
            [annotations addObject:item];

            NSMutableDictionary *dic =[[NSMutableDictionary alloc]init];
            [dic setObject:item.title forKey:@"name"];
            [dic setObject:item.subtitle forKey:@"subtitle"];

            [dic setObject:[NSNumber numberWithDouble:item.coordinate.longitude] forKey:@"longitude"];
            [dic setObject:[NSNumber numberWithDouble:item.coordinate.latitude] forKey:@"latitude"];

            [_dataArray addObject:dic];
        }
        [_table reloadData];
        [_mapView addAnnotations:annotations];
        [_mapView showAnnotations:annotations animated:YES];
    } else if (error == BMK_SEARCH_AMBIGUOUS_ROURE_ADDR){
        echo(([NSString stringWithFormat:@"起始点有歧义"]));

    } else {
        // 各种情况的判断。。。
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 65;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellID = [NSString stringWithFormat:@"Cell_%@", NSStringFromClass([UITableViewCell class])];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        UILabel *textLab=[[UILabel alloc]initWithFrame:CGRectMake(25, 10, WindowWidth-25, 18)];
        textLab.font =F(15);
        textLab.tag=100;
        [cell.contentView addSubview:textLab];
        UILabel *detailLab=[[UILabel alloc]initWithFrame:CGRectMake(25, 35, WindowWidth-25, 30)];
        detailLab.font =F(10);
        detailLab.numberOfLines=0;
        detailLab.tag=200;
        detailLab.textColor =LightFontColor;
        [cell.contentView addSubview:detailLab];
        UILabel *line=[[UILabel alloc]initWithFrame:CGRectMake(25, 64.5, WindowWidth-25, 0.5)];
        line.tag =300;
        [cell.contentView addSubview:line];
    }
    cell.backgroundColor=[UIColor whiteColor];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    UILabel *textLab =[cell viewWithTag:100];
    UILabel *detailLab =[cell viewWithTag:200];
    UILabel *line =[cell viewWithTag:300];
    line.backgroundColor =LineColor;
    NSDictionary *dic =[_dataArray objectAtIndex:indexPath.row];
    cell.backgroundColor =[UIColor clearColor];
    if(indexPath.row==0)
    {
        textLab.textColor=C(@"59beed");
    }else
    {
        textLab.textColor =FontColor;
    }
    textLab.text =[dic objectForKey:@"name"];
    detailLab.text =[dic objectForKey:@"subtitle"];
    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     NSDictionary *dic =[_dataArray objectAtIndex:indexPath.row];
    
    double longitude =[[dic objectForKey:@"longitude"]doubleValue];
    double latitude =  [[dic objectForKey:@"latitude"]doubleValue];
//坐标转换成地址
    isGeoSearch = false;
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){latitude,longitude};//初始化
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;//设置反编码的店为pt
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];//发送反编码请求.并返回是否成功
    if(flag)
    {
        echo(@"反geo检索发送成功");
    }
    else
    {
        echo(@"反geo检索发送失败");
    }
    [_dict setObject:[dic objectForKey:@"name"] forKey:@"name"];
    [_dict setObject:[dic objectForKey:@"subtitle"] forKey:@"subtitle"];
    [_dict setObject:[NSNumber numberWithDouble:latitude] forKey:@"latitude"];
    [_dict setObject:[NSNumber numberWithDouble:longitude] forKey:@"longitude"];
    self.backLocation(_dict);
    [self backController];
}

//坐标转换成地址
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    //返回城市
    if (error == 0) {
        //        BMKAddressComponent
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_dict setObject:result.addressDetail.city forKey:@"city"];
        [_dict setObject:result.addressDetail.province forKey:@"province"];
//        self.backLocation(_dict);
    }

    //第一次列表
    NSMutableArray *annotations = [NSMutableArray array];

    for (int i = 0; i < result.poiList.count; i++) {

        BMKPoiInfo* poi = [result.poiList objectAtIndex:i];
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = poi.pt;
        item.title = poi.name;
        item.subtitle =poi.address;
        [annotations addObject:item];
            
        NSMutableDictionary *dic =[[NSMutableDictionary alloc]init];
        [dic setObject:item.title forKey:@"name"];
        [dic setObject:item.subtitle forKey:@"subtitle"];
        [dic setObject:[NSNumber numberWithDouble:item.coordinate.longitude] forKey:@"longitude"];
        [dic setObject:[NSNumber numberWithDouble:item.coordinate.latitude] forKey:@"latitude"];
        [_dataArray addObject:dic];
        }
        [_table reloadData];

   
    
    
}


@end
